﻿using System;
using System.Activities;
using System.ComponentModel;
using System.Collections.Generic;
using System.Net;

namespace Vision.Core.ActivityComponents.Services
{
    /// <summary>
    /// 
    /// </summary>
    [System.ComponentModel.Designer(typeof(WebServiceContextDesigner))]
    public class WebServiceContext : NativeActivity
    {
        internal Components.DynamicWebService DynamicWebService { get; set; } 

        /// <summary>
        /// 
        /// </summary>
        [Browsable(false)]
        [DefaultValue(null)]
        public Activity Body { get; set; }

        /// <summary>
        /// 
        /// </summary>
        [DefaultValue(null)]
        [Category("Input")]
        public InArgument<string> ServiceWsdlUrl { get; set; }

        [DefaultValue(null)]
        [Category("Input")]
        public InArgument<NetworkCredential> ServiceCredentials { get; set; }

        /// <summary>
        /// 
        /// </summary>
        [DefaultValue(Components.DynamicWebService.HttpProtocol.Soap)]
        [Category("Input")]
        public Components.DynamicWebService.HttpProtocol Protocol { get; set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        protected override void Execute(NativeActivityContext context)
        {
            if (this.Body != null){
                this.DynamicWebService = new Components.DynamicWebService();
                this.DynamicWebService.WsdlUrl = this.ServiceWsdlUrl.Get(context);
                this.DynamicWebService.Credentials = this.ServiceCredentials.Get(context);                
                this.DynamicWebService.Protocol = this.Protocol;                
                this.DynamicWebService.InitService();                
                context.Properties.Add("9d40e1ff-4d19-46c1-a77e-348a229c6acc", this.DynamicWebService);
                context.ScheduleActivity(this.Body, this.OnChildActivityCompleted); 
            }            
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <param name="completedInstance"></param>
        private void OnChildActivityCompleted(NativeActivityContext context, ActivityInstance completedInstance)
        {
            context.Properties.Remove("9d40e1ff-4d19-46c1-a77e-348a229c6acc");
            this.DynamicWebService.Dispose();
        }
    }
}
